<template>
  <!-- 根据 isNewPerson 决定是否可以点击遮罩/ESC 关闭 -->
  <div class="box">
    <el-dialog v-model="visible" :show-close="!isNewPerson" :close-on-click-modal="false" :close-on-press-escape="false" align-center @close="handleClose">
      <template #header>
        <div class="dialog-header">
          <img v-if="isNewPerson" src="@/assets/images/text.png" alt="Logo" class="header-logo" />
          <img v-else src="@/assets/images/textold.png" alt="Logo" class="header-logo" />
        </div>
      </template>

      <template #default>
        <div v-if="isNewPerson">
          <p>完成企业认证，即可解锁平台全部功能，享受更多权益。</p>
          <p>认证通过后，您的企业信息将获得官方标识，提升买家的信任度，并有机会获得更多商机。</p>
        </div>
        <div v-else>
          <!-- <p>完成企业认证，即可解锁平台全部功能，享受更多权益。</p> -->
            <p>为了保障交易安全并享受完整服务，请在倒计时结束之前完成企业认证。</p>
          <!-- 倒计时 -->
          <div class="countdown">
            <div class="countdown-item">
              <div class="countdown-number">{{ countdown.days }}</div>
              <div class="countdown-label">天</div>
            </div>
            <div class="countdown-item">
              <div class="countdown-number">{{ countdown.hours }}</div>
              <div class="countdown-label">时</div>
            </div>
            <div class="countdown-item">
              <div class="countdown-number">{{ countdown.minutes }}</div>
              <div class="countdown-label">分</div>
            </div>
            <div class="countdown-item">
              <div class="countdown-number">{{ countdown.seconds }}</div>
              <div class="countdown-label">秒</div>
            </div>
          </div>
        </div>
      </template>

      <template #footer>
        <!-- <el-button v-if="!isNewPerson" @click="visible = false">以后再说</el-button> -->
        <el-button class="custom-auth-button" @click="goAuth">立即完成认证</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import baseService from "@/service/baseService";
import useView from "@/hooks/useView";
const POP_KEY = "AUTH_TIP_SHOWN"; // sessionStorage key
const hasShownInSession = () => sessionStorage.getItem(POP_KEY) === "1";
const markShownInSession = () => sessionStorage.setItem(POP_KEY, "1");
/* 弹窗控制 */
const visible = ref(false);
const isNewPerson = ref(false);

/* 接口返回的截止时间（yyyy-MM-dd HH:mm:ss） */
const deadlineStr = ref<string | null>(null);

/* 距离截止的剩余秒数 */
const leftSeconds = ref(0);
let timer: number | null = null;

/* 计算倒计时是否已过期 */
const isExpired = computed(() => leftSeconds.value <= 0);

/* 计算属性：是否可以关闭弹窗（过期时强制不可关） */
const canClose = computed(() => !isExpired.value);

/* 倒计时拆分：天/时/分/秒 */
const countdown = computed(() => {
  const total = leftSeconds.value;
  const d = Math.floor(total / 86400);
  const h = Math.floor((total % 86400) / 3600);
  const m = Math.floor((total % 3600) / 60);
  const s = total % 60;
  return {
    days: d,
    hours: h.toString().padStart(2, "0"),
    minutes: m.toString().padStart(2, "0"),
    seconds: s.toString().padStart(2, "0")
  };
});
function handleClose() {
  if (!isNewPerson.value) {
    markShownInSession(); // ★ 关键：只要关一次就记住
  }
  visible.value = false;
  clearTimer();
}

/* 拉取认证状态 */
async function fetchStatus() {
  try {
    const res = await baseService.get("/noc/authcompanyaudit/getStatusAndNewPerson");
    if (res.code === 0) {
      const { status, isNewPerson: newFlag, deadline } = res.data || {};
      isNewPerson.value = newFlag === "1";
      deadlineStr.value = deadline || null;

      /*visible.value = status === "0"; // 未认证才弹
      if (visible.value && deadlineStr.value) {
        startCountdown();
      }*/
      // ① 未认证 ② 会话里没弹过 → 才弹
      if (status === "0" && !hasShownInSession()) {
        visible.value = true;
        if (deadlineStr.value) startCountdown();
      }
    }
  } catch {
    /* 静默失败 */
  }
}

/* 启动倒计时 */
function startCountdown() {
  if (!deadlineStr.value) return;
  const end = new Date(deadlineStr.value).getTime();

  const tick = () => {
    const now = Date.now();
    leftSeconds.value = Math.max(0, Math.floor((end - now) / 1000));
    if (leftSeconds.value > 0) {
      timer = setTimeout(tick, 1000);
    } else {
      clearTimer();
    }
  };
  tick();
}

function clearTimer() {
  if (timer) {
    clearTimeout(timer);
    timer = null;
  }
}

/* 跳转认证页 */
function goAuth() {
  handleClose(); // 复用同一把锁
  visible.value = false;
  state.closeCurrentTab();
  router.replace("/cnas/certification-results");
  // router.replace("/cnas/certification-process");
}

/* 关闭拦截：已过期时禁止关闭 */
function beforeClose(done: () => void) {
  if (!canClose.value) return;
  done();
}

onMounted(() => {
  fetchStatus();
});

onBeforeUnmount(() => {
  clearTimer();
});

/* useView 相关 */
import { reactive, toRefs } from "vue";
import router from "@/router";
const view = reactive({});
const state = reactive({ ...useView(view), ...toRefs(view) });
</script>

<style scoped lang="scss">
.box {
  :deep(.el-dialog) {
    background-color: pink;
    width: 500px;
  }

  :deep(.el-dialog__header) {
    width: 500px;
    height: 92px;
    background: url(https://img.js.design/assets/img/689d56c240d5d2a02e688b3f.png#95f0046a410fc34c36c47a43d87345b8);
    background-size: 100% 100%;
    background-repeat: no-repeat;
    background-position: 0 0;
    // color: #fff;
  }

  :deep(.el-dialog__headerbtn .el-dialog__close) {
    color: #ffffff !important;
    font-size: 18px;

    &:hover {
      color: #e6f7ff !important;
    }
  }

  .dialog-header {
    display: flex;
    align-items: center;
    padding: 20px;

    .header-logo {
      width: 394px;
      height: 29px;
      margin: auto auto;
    }
  }

  :deep(.el-dialog__body) {
    width: 500px;
    // height: 360px;
    background-color: #ffffff;
    padding: 20px;
    padding-bottom: 10px;

    p {
      font-size: 16px;
      font-weight: 400;
      letter-spacing: 0px;
      line-height: 30px;
      color: rgba(0, 0, 0, 1);
      text-align: justify;
      vertical-align: top;
      display: block;
      padding: 0 15px;

      &:nth-child(2) {
        border-radius: 10px;
        background: rgba(189, 214, 255, 0.5);
        padding: 15px;
      }
    }
  }

  :deep(.el-dialog__footer) {
    width: 500px;
    // height: 100px;
    background-color: #ffffff;
    padding: 0 20px 30px;

    .el-button {
      width: 445px !important;
      height: 35px !important;
      border-radius: 8px !important;
      background: linear-gradient(270deg, rgba(77, 181, 255, 1) 0%, rgba(22, 119, 255, 1) 53.47%, rgba(87, 185, 255, 1) 100%) !important;
      border: none !important;
      color: #ffffff !important;
      font-size: 14px !important;
      font-weight: 500 !important;

      &:hover {
        background: linear-gradient(270deg, rgba(87, 191, 255, 1) 0%, rgba(32, 129, 255, 1) 53.47%, rgba(97, 195, 255, 1) 100%) !important;
      }

      &:active {
        background: linear-gradient(270deg, rgba(67, 171, 255, 1) 0%, rgba(12, 109, 255, 1) 53.47%, rgba(77, 175, 255, 1) 100%) !important;
      }
    }
  }
}

.custom-auth-button {
  width: 445px !important;
  height: 35px !important;
  border-radius: 8px !important;
  background: linear-gradient(270deg, rgba(77, 181, 255, 1) 0%, rgba(22, 119, 255, 1) 53.47%, rgba(87, 185, 255, 1) 100%) !important;
  border: none !important;
  color: #ffffff !important;
  font-size: 14px !important;
  font-weight: 500 !important;

  &:hover {
    background: linear-gradient(270deg, rgba(87, 191, 255, 1) 0%, rgba(32, 129, 255, 1) 53.47%, rgba(97, 195, 255, 1) 100%) !important;
  }

  &:active {
    background: linear-gradient(270deg, rgba(67, 171, 255, 1) 0%, rgba(12, 109, 255, 1) 53.47%, rgba(77, 175, 255, 1) 100%) !important;
  }
}

.countdown {
  display: flex;
  justify-content: center;
  align-items: center;
  gap: 8px;
  margin: 20px 0;
  padding: 0 15px;

  .countdown-item {
    display: flex;
    align-items: center;
    gap: 4px;

    .countdown-number {
      width: 50px;
      height: 40px;
      background: #e0f0ff;
      border-radius: 8px;
      display: flex;
      align-items: center;
      justify-content: center;
      font-size: 20px;
      font-weight: bold;
      color: #ff8c00;
    }

    .countdown-label {
      font-size: 14px;
      color: #333;
      font-weight: 400;
    }
  }
}
</style>
